using MvcApplication1.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Script.Serialization;

namespace MvcApplication1.Controllers
{
    public class BreezeSampleShellController : Controller
    {
        public ActionResult Index()
        {
            BreezeSampleTodoItem td = new BreezeSampleTodoItem();
            return View(td);
        }


        [HttpGet]
        public ActionResult Mappingdata(string model, string BreezeController)
        {
            #region ViewModel
            BreezeSampleTodoItem data = new BreezeSampleTodoItem();

            List<string> PropertyList = new List<string>();
            string str = "";
            string script = "";
            script += "var manager = new breeze.EntityManager('breeze/" + BreezeController + "'); ";
            script += "var vm = { ";
            //Declare property in viewmodel from model
            foreach (PropertyInfo prop in typeof(BreezeSampleTodoItem).GetProperties())
            {
                str = prop.Name;  
                var property = data.GetType().GetProperty(str);              
                string value = property.PropertyType.Name;
                if (value != "ICollection`1")
                {
                    if (str != "Id")
                    {
                        script += str + ": ko.observable(''), ";
                        //Store property name
                        PropertyList.Add(str);
                    }
                    
                }
                else
                {
                    script += str + ": ko.observableArray(), ";
                    //Store property name
                    PropertyList.Add(str + "_Marr");
                }
            }
            script += "childhost: ko.observable(''), ";
            script += "items: ko.observableArray(), ";
            script += "removeItem: removeItem";
            script += "};";
            #endregion
            #region getAllTodos
            script += " function getAllTodos() { ";
            script += "var query = new breeze.EntityQuery()";
            script += ".from('Todos')";
            script += ".expand('BreezeSampleChildItems');";
            script += "return manager.executeQuery(query);";
            script += "}";
            #endregion
            #region querySucceeded
            script += "function querySucceeded(data) { ";
            script += "vm.items([]); ";
            script += "data.results.forEach(function (item) {";
            script += " vm.items.push(item);";
            script += "}); }";
            #endregion
            #region AddItem
            script += "function addItem() { ";
            script += "var item = manager.createEntity('" + model + "'); ";

            //script += "item.setProperty('Question', vm.Question()); ";
            foreach (string name in PropertyList)
            {
                if (!name.EndsWith("_Marr"))
                {
                    if(name != "Id"){
                        script += "item.setProperty('" + name + "', vm." + name + "()); ";
                    }    
                }
                else
                {
                    string pname = name.Substring(0, name.LastIndexOf("_Marr"));
                    script += "for (var i = 0; i < vm.BreezeSampleChildItems().length; i++){ ";
                    script += "    item." + pname + ".push(vm.BreezeSampleChildItems()[i]);} ";
                }
            }         

            script += "    extendItem(item); ";
            script += "    vm.items.push(item); ";
            script += "    }";
            #endregion
            #region Addchild
            script += "function addChild(index) { ";    
            script += "var item = createchild({ ";
            script += "    Host: vm.childhost() ";
            script += "}); ";
            script += "vm.items()[index].BreezeSampleChildItems.push(item); ";
            script += "} ";
            #endregion
            #region Extendingitem
            script += "function extendItem(item) { ";
            script += "if (item.isEditing) return; ";
            script += "item.isEditing = ko.observable(false); ";
            script += "item.entityAspect.propertyChanged.subscribe(function () { ";
            script += "   if (suspendItemSave) { return; } ";
            script += "   setTimeout(saveIfModified, 0); ";           
            script += "   function saveIfModified() { ";
            script += "        if (item.entityAspect.entityState.isModified()) { ";
            script += "            saveChanges(); ";
            script += "        } ";
            script += "   } ";
            script += "}); ";
            script += "}";
            #endregion
            #region Savechanges
            script += "function saveChanges() { ";
            script += "return manager.saveChanges();} ";
            #endregion
            #region CreateTodo
            script += "function createTodo() { ";
            script += "return manager.createEntity('BreezeSampleTodoItem');} ";
            #endregion
            #region Createchild
            script += "function createchild(initialValues) { ";
            script += "return manager.createEntity('BreezeSampleChildItem', initialValues);} ";
            #endregion
            #region SaveAll
            script += "function WantEdit(item) { ";
            script += "saveChanges(); ";
            script += "alert('Save successfull');} ";
            #endregion

            #region Delete
            script += "function removeItem(item) { ";
            script += "vm.items.remove(item); ";
            script += "item.entityAspect.setDeleted(); ";
            script += "saveChanges();} ";
            //remove child item
            script += "function removeChildItem(par,child) { ";
            script += "var ite = vm.items()[par].BreezeSampleChildItems()[child];";
            script += "vm.items()[par].BreezeSampleChildItems.remove(ite)";        
            script += "} ";

            #endregion

            script += "$(document).ready(function () { ";
            script += "getAllTodos().then(querySucceeded); ";
            script += "ko.applyBindings(vm); ";   
            script += "});";

            return JavaScript(script);
        }

    }
}
